package com.zenithmind.version.pojo.dto.base;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;

import java.util.Set;

/**
 * 基础DTO类 - 遵循单一职责原则，提供通用的验证功能
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
public abstract class BaseDTO {

    private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
    private static final Validator VALIDATOR = VALIDATOR_FACTORY.getValidator();

    /**
     * 验证DTO对象
     * 
     * @return 验证结果集合
     */
    public Set<ConstraintViolation<BaseDTO>> validate() {
        return VALIDATOR.validate(this);
    }

    /**
     * 检查DTO对象是否有效
     * 
     * @return 是否有效
     */
    public boolean isValid() {
        return validate().isEmpty();
    }

    /**
     * 获取验证错误信息
     * 
     * @return 错误信息字符串
     */
    public String getValidationErrors() {
        Set<ConstraintViolation<BaseDTO>> violations = validate();
        if (violations.isEmpty()) {
            return null;
        }
        
        StringBuilder errors = new StringBuilder();
        for (ConstraintViolation<BaseDTO> violation : violations) {
            if (errors.length() > 0) {
                errors.append("; ");
            }
            errors.append(violation.getPropertyPath()).append(": ").append(violation.getMessage());
        }
        return errors.toString();
    }

    /**
     * 验证并抛出异常
     * 
     * @throws IllegalArgumentException 验证失败时抛出
     */
    public void validateAndThrow() {
        String errors = getValidationErrors();
        if (errors != null) {
            throw new IllegalArgumentException("验证失败: " + errors);
        }
    }
}
